﻿using System.Windows;
using System.Windows.Data;
using nRoute.Components;
using nRoute.Behaviors.Interactivity;
using System.ComponentModel;

namespace nRoute.Behaviors
{
    public class BridgeValueBehavior
		 : BindableBehavior<FrameworkElement>
    {
        public static readonly DependencyProperty ValueRelayProperty =
            DependencyProperty.Register("ValueRelay", typeof(ValueRelay), typeof(BridgeValueBehavior),
                new PropertyMetadata(null, OnValueRelayChanged));

        public static readonly DependencyProperty ValueSourceProperty =
            DependencyProperty.Register("ValueSource", typeof(object), typeof(BridgeValueBehavior),
                new PropertyMetadata(null, OnValueSourceChanged));

#region Properties

        [Category("Common Properties")]
        public ValueRelay ValueRelay 
        {
            get { return (ValueRelay)GetValue(ValueRelayProperty); }
            set { SetValue(ValueRelayProperty, value); }
        }

        [Category("Common Properties")]
#if SILVERLIGHT
        [TypeConverter(typeof(nRoute.Components.TypeConverters.ConvertFromStringConverter))]
#endif
        public object ValueSource
        {
            get
            {
                return GetValue(ValueSourceProperty);
            }
            set
            {
                SetValue(ValueSourceProperty, value);
            }
        }

#if SILVERLIGHT

        [Category("Common Properties")]
        public Binding ValueSourceBinding
        {
            get { return GetBinding(ValueSourceProperty); }
            set { SetBinding<object>(ValueSourceProperty, value); }
        }

#endif

#endregion

#region Handlers

        private static void OnValueSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((BridgeValueBehavior)d).UpdateRelay();
        }

        private static void OnValueRelayChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((BridgeValueBehavior)d).UpdateRelay();
        }

#endregion

#region Overrides

        protected override void OnAttached()
        {
            base.OnAttached();
            UpdateRelay();
        }

#endregion

#region Helpers
        
        private void UpdateRelay()
        {
            if (ValueRelay != null && this.ValueSource != null)
            {
                ValueRelay.Value = ValueSource;
            }
        }

#endregion

    }
}
